﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using AvaloniaApplication1.Component.ViewModel;
using AvaloniaApplication1.IServices;
using AvaloniaApplication1.Models;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Modbus.Device;
using SukiUI.Dialogs;

namespace AvaloniaApplication1.ViewModels.ModbusCardViewModel;

public partial class ModbusTcpConfigViewModel:ObservableObject
{
    [ObservableProperty]
    private string _deviceName;
    [ObservableProperty]
    private string _severIp;
    [ObservableProperty]
    private string _tcpName;
    [ObservableProperty]
    private Dictionary<string, int> _ports= new();
    [ObservableProperty]
    private int _timeOut;
    [ObservableProperty] private IModbusManager _modbusManager;
    // 引用 InfoBar 组件的 ViewModel
    [ObservableProperty] private InfoViewModel _inforBar;
    
    public ModbusTcpConfigViewModel(string deviceName,IModbusManager modbusManager)
    {
        DeviceName = deviceName;
        ModbusManager = modbusManager;
        InforBar = new InfoViewModel();
        var modbusConfigs =  ModbusManager.GetModbusDevice(DeviceName);
        SeverIp=modbusConfigs.TcpConfig.Server;
        Ports=modbusConfigs.TcpConfig.Ports;
        TimeOut=modbusConfigs.TcpConfig.Timeout;
        TcpName=modbusConfigs.TcpConfig.TcpName;
    }
    /// <summary>
    /// 保存Tcp配置
    /// </summary>
    [RelayCommand]
    public async Task SaveTcpConfig()
    {
        var result = await ModbusManager.ConfigureDeviceAsync(DeviceName, SeverIp, TcpName,Ports, TimeOut);
        InforBar.ShowInfo(result ? "保存成功" : "保存失败");
    }
    

}